package com.gorkr.labuladong.data_struct.array.binary_search;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author gorkr
 * @date 2022/06/07 15:17
 **/
public class M34FindFirstAndLastPositionOfElementInSortedArray {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[2];
        res[0] = leftSearch(nums, target);
        res[1] = rightSearch(nums, target);
        return res;
    }

    private int leftSearch(int[] nums, int target) {
        // 左闭右开
        int left = 0, right = nums.length;
        int mid;
        while (left < right) {
            mid = (left + right) / 2;
            if (target == nums[mid]) {
                right = mid;
            } else if (target < nums[mid]) {
                right = mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            }
        }
        if (left >= nums.length) {
            return -1;
        }
        return nums[left]==target?left:-1;
    }

    private int rightSearch(int[] nums, int target) {
        // 左闭右开
        int left = 0, right = nums.length;
        int mid;
        while (left < right) {
            mid = (left + right) / 2;
            if (target == nums[mid]) {
                left = mid + 1;
            } else if (target < nums[mid]) {
                right = mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            }
        }


        if(right<=0){
            return -1;
        }
        return nums[right-1]==target?right-1:-1;

    }

    @Test
    public void test(){
        int[] nums = {5,7,7,8,8,10};
        int target = 8;
        System.out.println(Arrays.toString(searchRange(nums, 5)));
    }

}
    